package cn.yuznu.www;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBC { //       处理数据库操作
    private static final String DB_URL = "jdbc:mysql://127.0.0.1:3306/ChatDB";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "1538389602";

    // 登录验证
    public static boolean login(String username, String password) {
        String sql = "SELECT * FROM Users WHERE username =? AND password =?";
        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, username);
            pstmt.setString(2, password);

            ResultSet resultSet = pstmt.executeQuery();
            return resultSet.next();
        } catch (SQLException e) {
            System.out.println("登录时SQL异常：" + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    // 用户注册方法
    public static boolean register(String username, String password) {
        String sql = "INSERT INTO Users (username, password) VALUES (?,?)";
        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, username);
            pstmt.setString(2, password);

            int affectedRows = pstmt.executeUpdate();
            return affectedRows > 0;
        } catch (SQLException e) {
            System.out.println("注册时SQL异常：" + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }


    private static Connection getConnection() throws SQLException { // 静态方法，返回一个数据库连接对象
        return DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); // 使用驱动管理器获取数据库连接
    }
}